# coding=utf-8
"""
Created on 2018年09月06日
"""
import weakref
from util_base.ufo_decorators import processor
from common_base.cmd import CMD
from processor_base.base_processor import BaseProcessor
from util_base.exception import ParamException, UFOException as E
from common_base.errors import AliveError
from common_base.constants import BannerState, UFOConstant, KeywordActiveType, BannerType
from service_base.article_service import ArticleService
from setting_base.setting import C


@processor(CMD.CMD_UGC_GET_DISCOVERY_DATA, internal_access=True)
class GetDiscoveryData(BaseProcessor):
    """
    GetDiscoveryData
    """
    
    TAG = 'GetDiscoveryData'
    
    def __init__(self, handler):
        """
        Constructor
        """
        BaseProcessor.__init__(self, handler)
        self._article_service = ArticleService(weakref.proxy(self))
        self.download_url = C('storage')['download']['url']

    def process(self):
        """
        process protocol
        """
        userid = self.alive_cmsdb.get_userid_by_userkey(self.user_key)
        if not userid:
            raise E(AliveError.ERROR_USER_DOES_NOT_EXIST)

        # banner
        db_banner_list = self.alive_cmsdb.get_banner_list(state=BannerState.ONLINE)
        return_banner_list = self.deal_banners_data(userid, db_banner_list)

        # weekly hot articles
        db_weekly_hot_articles = self.alive_cmsdb.get_weekly_hot_articles(
            userid, page_size=UFOConstant.PAGE_SIZE_SEARCH_TAG_WEEKLY_HOT_ARTICLES
        )
        weekly_hot_articles = self._article_service.batch_deal_articles_return_data(
            userid, db_weekly_hot_articles, comments_page_size=0, article_author_info=False, do_i_liked=False
        )

        # keyword new articles
        keywordArticles = self.get_keyword_articles(userid)

        return dict(
            bannerList=return_banner_list,
            weeklyHotArticles=weekly_hot_articles,
            keywordArticles=keywordArticles
        )

    def deal_banners_data(self, userid, db_banner_list):
        """
        处理banner数据
        """
        return_banner_list = list()

        # banner type is article
        article_id_list = [e['article_id'] for e in db_banner_list if e['banner_type'] == BannerType.Article]
        article_dict_data = dict()
        if article_id_list:
            article_id_list = list(set(article_id_list))
            db_articls = self.alive_cmsdb.get_articles_by_article_id_list(article_id_list)
            article_base_data = self._article_service.batch_deal_articles_return_data(
                userid, db_articls, comments_page_size=0, article_author_info=False, do_i_liked=False
            )
            article_dict_data = {e['articleId']: e for e in article_base_data}

        for each_banner in db_banner_list:
            image_url = each_banner['image_url']
            banner_type = each_banner['banner_type']
            article_id = each_banner['article_id']
            this_banner = dict(
                bannerId=each_banner['banner_id'],
                bannerType=banner_type,
                imageUrl=self.download_url + image_url if image_url else '',
                jumpType=each_banner['jump_type'],
                jumpInfo=each_banner['jump_info'],
                interval=each_banner['interval'],
                articleInfo=article_dict_data.get(article_id) if banner_type == BannerType.Article else dict()

            )
            return_banner_list.append(this_banner)

        return return_banner_list

    def get_keyword_articles(self, userid):
        """
        获取用户keywordId为key, articles为value的dict数据
        """
        db_keywords = self.alive_cmsdb.get_keywords_by_active_type(KeywordActiveType.Active)
        keyword_id_list = [e['keywordId'] for e in db_keywords]

        # 数据库中查出的每个keyword按点赞倒序排在前N的帖子
        db_keyword_articles = self.alive_cmsdb.get_search_tab_keyword_articles(
            userid, keyword_id_list, UFOConstant.PAGE_SIZE_SEARCH_TAG_KEYWORD_ARTICLES
        )

        # 调用service组装帖子信息
        keyword_articles_base_data = self._article_service.batch_deal_articles_return_data(
            userid, db_keyword_articles, comments_page_size=0, article_author_info=False, do_i_liked=False
        )
        key_articleId_value_articleInfo_dict = {e['articleId']: e for e in keyword_articles_base_data}

        # 以keyword为key, articleInfoList为value的结构
        key_keywordId_value_articleInfoList_dict = dict()
        for i_db_keyword_article in db_keyword_articles:
            keyword_id = i_db_keyword_article['keywordId']
            article_id = i_db_keyword_article['articleId']
            if keyword_id not in key_keywordId_value_articleInfoList_dict.keys():
                key_keywordId_value_articleInfoList_dict[keyword_id] = list()
            this_article_info = key_articleId_value_articleInfo_dict.get(article_id)
            if this_article_info:
                key_keywordId_value_articleInfoList_dict[keyword_id].append(this_article_info)

        # 获取keyword下面帖子的数量
        keyword_articles_num = self.alive_cmsdb.count_keyword_articles_num(keyword_id_list)
        keyword_articles_num_dict = {e['keywordId']: e['total_data'] for e in keyword_articles_num}

        # 组装帖子的返回信息(保证keyword的顺序)
        return_keyword_articles = list()
        for each_keyword in db_keywords:
            keyword_id = each_keyword['keywordId']
            this_keyword_articles = dict(
                keywordId=keyword_id,
                keyword=each_keyword['keyword'],
                color=each_keyword['color'],
                type=each_keyword['type'],
                article_num=keyword_articles_num_dict.get(keyword_id, 0),
                Articles=key_keywordId_value_articleInfoList_dict.get(keyword_id, list())
            )
            return_keyword_articles.append(this_keyword_articles)

        return return_keyword_articles

    def _verify_params(self):
        """
        重写父类方法, 作参数校验
        """
